<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <template #header>
        <el-button
          @click="addTrademark"
          type="primary"
          size="default"
          :icon="Plus"
          >添加</el-button
        >
      </template>
      <el-table
        :style="{ marginBottom: '30px' }"
        :data="tableData"
        border
        stripe
      >
        <el-table-column label="序号" align="center" type="index" width="80" />
        <el-table-column label="商品名称" prop="tmName" />
        <el-table-column label="产品LOGO" prop="logoUrl">
          <template #default="{ row }">
            <el-image
              :style="{ height: '100px' }"
              :lazy="true"
              :src="row.logoUrl"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              :icon="Edit"
              @click="updateTrademark(row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="deleteTrademark(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:page-size="limit"
        v-model:current-page="page"
        :total="total"
        :page-sizes="[3, 5, 7, 9, 10]"
        :pager-count="5"
        layout="prev,pager,next,sizes,jumper,total"
        background
      />
    </el-card>

    <!-- 添加修改品牌的弹窗 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="newTrademark.id ? '修改品牌' : '添加品牌'"
    >
      <el-form
        label-width="100px"
        ref="ruleFormRef"
        :rules="trademarkRule"
        :model="newTrademark"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input autocomplete="off" v-model="newTrademark.tmName" />
        </el-form-item>
        <el-form-item label="品牌Logo" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${baseUrl}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <el-image
              v-if="newTrademark.logoUrl"
              :src="newTrademark.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addOfUpdateTrademark"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
import { onMounted, ref, toRefs, watch, reactive } from "vue";
import {
  requestAddTrademark,
  requestDeleteTrademark,
  requestTrademarkList,
  requestUpdateTrademark,
} from "@/api/Trademark";
import type {
  trademarkRecordsListType,
  trademarkRecordsItemType,
} from "@/api/Trademark";
import { Plus, Delete, Edit } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, type FormInstance } from "element-plus";
import type { UploadProps, FormRules } from "element-plus";

//1.获取品牌数据列表
//品牌列表表格数据
const tableData = ref<trademarkRecordsListType>([]);

//页码数据类型
interface pageDataType {
  page: number;
  limit: number;
  total: number;
}
//页码数据
const pageData = ref<pageDataType>({
  page: 1,
  limit: 3,
  total: 100,
});
//将页码的数据解构
const { page, limit, total } = toRefs(pageData.value);

//页码变更或每页的条目变更触发，请求新的列表
watch([page, limit], () => {
  getTrademarkList();
});

//获取品牌列表的请求函数
const getTrademarkList = async () => {
  const result = await requestTrademarkList({
    page: page.value,
    limit: limit.value,
  });
  tableData.value = result.records;
  total.value = result.total;
};

//初始化的时候请求数据
onMounted(() => {
  getTrademarkList();
});

//2.添加更新品牌的逻辑
const dialogFormVisible = ref(false);
const baseUrl = import.meta.env.VITE_API_URL;
//创建一个新的品牌数据
const newTrademark = ref<trademarkRecordsItemType>({
  logoUrl: "",
  tmName: "",
  id: 0,
});

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  newTrademark.value.logoUrl = URL.createObjectURL(uploadFile.raw!);
  //将上传返回的数据给到新的品牌
  newTrademark.value.logoUrl = response.data;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type !== "image/jpeg" &&
    rawFile.type !== "image/webp" &&
    rawFile.type !== "image/png"
  ) {
    ElMessage.error("图片文件格式不支持");
    return false;
    //rawFile是字节
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Logo文件不能大于2mb");
    return false;
  }
  return true;
};
//添加品牌的逻辑
const addTrademark = () => {
  //每次添加将上次的校验信息清除
  ruleFormRef.value?.clearValidate();
  //让弹窗显示的api
  dialogFormVisible.value = true;
  //每次添加，将数据初始化
  newTrademark.value = {
    logoUrl: "",
    tmName: "",
    id: 0,
  };
};
//更新修改数据的回填
const updateTrademark = (row: trademarkRecordsItemType) => {
  //每次修改将上次的校验信息清除
  ruleFormRef.value?.clearValidate();
  dialogFormVisible.value = true;
  newTrademark.value = { ...row };
};
//更新和添加的请求
const addOfUpdateTrademark = async () => {
  try {
    //表单的全局校验，返回一个promise，如果校验不通过返回一个失败promise
    await ruleFormRef.value?.validate();
    //将弹窗关闭
    dialogFormVisible.value = false;
    //将id转为布尔值，通过判断是否存在id判断是修改还是添加
    const isId = !!newTrademark.value.id;
    try {
      //有则修改
      if (isId) {
        await requestUpdateTrademark(newTrademark.value);
        ElMessage.success("修改数据成功");
        //无则添加
      } else {
        await requestAddTrademark(newTrademark.value);
        ElMessage.success("添加数据成功");
      }
      //重新发起请求
      getTrademarkList();
    } catch (e) {
      ElMessage.warning(isId ? "修改数据错误" : "添加数据错误");
    }
  } catch (e) {
    ElMessage.warning("请填写合法的值");
  }
};

//3.删除品牌的逻辑
const deleteTrademark = async (id: number) => {
  //使用ElMessageBox弹窗组件，第一个参数为描述信息，第二个参数为标题，第三个参数是弹窗的配置
  ElMessageBox.confirm("你确定要删除吗", "警告！！", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    //then表示成功的回调
    .then(async () => {
      //捕获错误
      try {
        await requestDeleteTrademark(id);
        getTrademarkList();
        ElMessage.success("删除成功");
      } catch (e) {
        ElMessage.error("删除失败");
      }
    })
    //catch失败的回调
    .catch(() => {
      ElMessage.warning("取消删除");
    });
};

//4.表单的校验
//表单每一项的规则
//自定义表单规则,value是需要被校验的字段，callback类似路由守卫的next
const checkTmNameLength = (rule: any, value: string, callback: any) => {
  if (value.length < 2 || value.length > 5) {
    callback("品牌长度请在2到5个字之间");
  }
  callback();
};
//获取表单实例，然后在分别在添加修改提交的时候全局校验，在每次打开弹窗的时候将上一次的校验信息清除
const ruleFormRef = ref<FormInstance>();

const trademarkRule = reactive<FormRules>({
  tmName: [
    { required: true, message: "必须填写品牌名称", trigger: "blur" },
    // { min: 2, max: 5, message: "品牌长度请在2到5个字之间", trigger: "blur" },
    {
      validator: checkTmNameLength,
      message: "品牌长度请在2到5个字之间",
      trigger: "blur",
    },
  ],
  logoUrl: [{ required: true, message: "请上传图片", trigger: "change" }],
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
